import React, { Fragment, useCallback, useEffect, useState } from 'react'
import { Spinner } from '@blueprintjs/core'
import cn from 'classnames'
import Pagination from 'components/Pagination'
import MusicList from 'components/MusicList'
import { TABS } from 'constants/search'
import useQuery from 'hooks/useQuery'
import useAsyncFn from 'hooks/useAsyncFn'
import search from 'apis/search'
import { PAGE, PAGE_SIZE } from 'constants/pagination'
import styles from './style.module.css'
const Search = () => {
  const { keyword } = useQuery()
  const [page, setPage] = useState(PAGE)
  const [activeTab, setActiveTab] = useState(TABS.MUSIC.tabKey)
  const { unit, key, searchType, tab } = TABS[activeTab]
  const [state, searchFn] = useAsyncFn(search.search)
  const { value: res, loading } = state
  const total = res?.[`${key}Count`] || 0
  useEffect(() => {
    searchFn({
      type: searchType,
      keywords: keyword,
    })
  }, [keyword])
  const handleTabClick = useCallback(
    (key: string) => {
      setActiveTab(key)
      const { searchType } = TABS[key]
      searchFn({
        type: searchType,
        keywords: keyword,
      })
    },
    [keyword],
  )
  const handlePageChange = useCallback(
    (page: number) => {
      setPage(page)
      searchFn({
        type: searchType,
        keywords: keyword,
        offset: (page - 1) * PAGE_SIZE,
      })
    },
    [keyword],
  )
  return (
    <div className={styles.root}>
      <div className={styles.header}>
        <div className={styles.title}>
          <span className={styles.keyword}>{keyword}</span>
          <span className={styles.count}>
            找到 {total} {unit} {tab}
          </span>
        </div>
      </div>
      <div className={styles.tabs}>
        {Object.keys(TABS).map((key) => (
          <div
            className={cn(styles.tab, activeTab === key && styles.active)}
            key={key}
            onClick={() => handleTabClick(key)}
          >
            {TABS[key].tab}
          </div>
        ))}
      </div>
      <div className={styles.content}>
        {loading ? (
          <Spinner />
        ) : (
          <Fragment>
            {activeTab === TABS.MUSIC.tabKey && <MusicList data={res?.songs} />}
            <div className='pagination'>
              <Pagination total={total} page={page} onPageChange={handlePageChange} />
            </div>
          </Fragment>
        )}
      </div>
    </div>
  )
}

export default Search
